/*   
 * Copyright (c) 2011, TUgether, TU Braunschweig
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
 /**
 * @author Mohamed Karray <mohamed.karray@gmx.de>
 *
 */
 

package de.tu_bs.tugether.liferayunit.liferayPages;

import java.net.URL;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

import de.tu_bs.tugether.liferayunit.liferayElements.portlets.LoginPortlet;
import de.tu_bs.tugether.liferayunit.util.LiferayUtil;

public class LoginPage extends MaximizedPortletPage<LoginPortlet>   implements ILoginPage{
	
	public final static String XPATH_KEY_LOGIN_PORTLET = "LoginPortlet";
	public final static String XPATH_KEY_IS_IN_LOGIN_PAGE = "isInLoginPage ";
	
	
	public LoginPage(HtmlPage htmlPage) throws Exception {
		super(htmlPage);
	}

	
	public LoginPage(URL url, BrowserVersion browserVersion, String proxyHost,
			int port) throws Exception {
		super(url, browserVersion, proxyHost, port);
		// TODO Auto-generated constructor stub
	}


	public LoginPage(URL url) throws Exception {
		super(url);
	}


	public void initialize() throws Exception{
		super.initialize();

		HtmlElement htmlElement = super.getFirstByXPathKey(XPATH_KEY_LOGIN_PORTLET);
		super.portlet =  new LoginPortlet(htmlElement,this);
		
		
	}

	public boolean isInLoginPage()  {
		return this.findElementWithXPathKey(XPATH_KEY_IS_IN_LOGIN_PAGE);
	}
	
	public String getErrorMessage(){
		LoginPortlet loginPortlet = getPortlet();
		return loginPortlet.getErrorMessage();
	}
	public LiferayPage login(String username, String password) throws Exception {
		LoginPortlet loginPortlet = getPortlet();
		HtmlPage page = loginPortlet.login(username,password);
		if (!LiferayUtil.isSignedIn(page)){
			logger.error("Login fehlgeschlagen!\n"+getErrorMessage());
			return new LoginPage(page);
		}
		logger.debug("Login erfolgreich!");
		return new LiferayPage(page) ;
	}


	
}
